import org.apache.log4j.Logger;

import java.io.FilterReader;
import java.io.IOException;
import java.io.Reader;

public class TrimSpacesReader extends FilterReader {
    private final static Logger log = Logger.getLogger(TrimSpacesReader.class);
    private Character prevChar;

    /**
     * Creates a new filtered reader.
     *
     * @param in a Reader object providing the underlying stream.
     * @throws NullPointerException if <code>in</code> is <code>null</code>
     */
    public TrimSpacesReader(Reader in) {
        super(in);
    }


    public int read(char cbuf[], int off, int len) throws IOException {
        if ((off < 0) || (off > cbuf.length) || (len < 0) ||
            ((off + len) > cbuf.length) || ((off + len) < 0)) {
            throw new IndexOutOfBoundsException();
        } else if (len == 0) {
            return 0;
        }

        char tmp[] = new char[len];
        int totalPutChars = 0;

        long readChars = 0;
        while(len > 0 && readChars != -1) {
            readChars = in.read(tmp, 0, len);

            if(log.isTraceEnabled()) {
                log.trace("readChars=" + readChars + ", len=" + len + ", prevChar=" + prevChar);
            }

            int j = 0;
            while(j < readChars) {
                if(log.isTraceEnabled()) {
                    log.trace("j=" + j + ", totalPutChars=" + totalPutChars + ", prevChar=" + prevChar + ", tmp[j]=" + tmp[j]);
                }

                char curChar = tmp[j];
                if( prevChar != null &&
                        !(prevChar == curChar && prevChar == ' ') &&
                        !(prevChar == ' ' && curChar == '\r') ) {
                    //cbuf[off + totalPutChars] = (prevChar == ' ' ? ';' : prevChar);
                    cbuf[off + totalPutChars] = prevChar;
                    totalPutChars++;
                }

                prevChar = curChar;
                j++;
            }

//            cbuf[off + totalPutChars] = prevChar;
//            totalPutChars++;

            len = len - totalPutChars;

            if(log.isTraceEnabled()) {
                log.trace("len=" + len + ", totalPutChars=" + totalPutChars + ", prevChar=" + prevChar);
            }
        }

        return (totalPutChars == 0 && readChars == -1) ? -1 : totalPutChars;
    }
}
